<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkAgent\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Corp\Utils\WeWorkFactory;
use MoChat\App\WorkAgent\Contract\WorkAgentContract;
use MoChat\App\WorkAgent\Event\ResetPermanentCodeRawEvent;
use Psr\Container\ContainerInterface;

/**
 * 重置永久授权码通知.
 *
 * @Listener(priority=9999)
 */
class ResetPermanentCodeRawListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var WeWorkFactory
     */
    private $weWorkFactory;

    /**
     * @var WorkAgentContract
     */
    private $workAgentService;

    /**
     * @var CorpContract
     */
    private $corpService;

    public function listen(): array
    {
        return [
            ResetPermanentCodeRawEvent::class,
        ];
    }

    public function process(object $event)
    {
        try {
            $message = $event->message;
            $loggerFactory = $this->container->get(LoggerFactory::class);
            $this->logger = $loggerFactory->get(__CLASS__);
            $this->weWorkFactory = $this->container->get(WeWorkFactory::class);
            $this->workAgentService = $this->container->get(WorkAgentContract::class);
            $this->corpService = $this->container->get(CorpContract::class);
            $this->logger->debug(sprintf('重置永久授权码通知监听器开始，消息体为：%s', Json::encode($message)));

            $authCode = $message['AuthCode'];

            $openApp = $this->weWorkFactory->getProviderApp($message['SuiteId']);
            $wxResult = $openApp->corp->getPermanentByCode($authCode);
            if (isset($wxResult['errcode'])) {
                $this->logger->warning(sprintf('获取永久授权码失败，错误信息：%s', $wxResult['errmsg']));
                return;
            }

            $openWxCorpId = $wxResult['auth_corp_info']['corpid'];
            $corp = $this->corpService->getCorpByOpenWxCorpId($openWxCorpId, ['id']);
            if (empty($corp)) {
                $this->logger->warning(sprintf('未找到该企业，企业ID：%s', $openWxCorpId));
                return;
            }

            $agent = $this->workAgentService->getWorkAgentCustomizedAppByCorpId((int) $corp['id'], ['id']);
            if (empty($agent)) {
                $this->logger->warning(sprintf('未找到代开发自建应用，企业ID：%s', $openWxCorpId));
                return;
            }

            $data = [
                'wx_secret' => $wxResult['permanent_code'],
            ];
            $this->workAgentService->updateWorkAgentById($agent['id'], $data);
            $this->logger->debug(sprintf('授重置永久授权码通知监听器执行成功'));
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('重置永久授权码通知监听器回调监听器失败，错误信息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
